﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{ await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml"); }
    @{ await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml"); }
    <script type="text/javascript" src="~/lib/echarts/extension/dataTool.js?v=@DateTime.Now.Ticks" asp-append-version="true"></script>

    <link href="/css/ToPnParmTrend.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>ToPnParmTrend</title>

    <style type="text/css">
        #datagrip {
            color: black;
            font-size: 0.125rem;
            overflow-y: auto;
        }

        .detail {
            color: black;
            height: 3rem;
            width: 100%;
        }

        #datagrip {
            color: black;
            background-color: #dfe4ee;
        }

        thead {
            color: black;
            text-align: center;
            margin: auto;
            position: sticky;
            top: 0;
            background-color: #a2c2e2;
        }

        thead > tr {
            color: black;
            font-size: 0.13rem;
            height: 0.5rem;
        }

        th, td {
            color: black;
            padding: 0.05rem;
            /*border: 1px solid #0aa9cd;*/
            border: 1px solid #c2c3c4;
        }

        tfoot {
            font-size: 0.13rem;
            position: sticky;
            bottom: 0;
            background-color: #a2c2e2; /*#a1e1e1*/
            /*height: 0.45rem;*/
        }

        .ZebraFail {
            color: black;
            background-color: #ffcccc;
        }

        .ZebraAbort {
            color: black;
            background-color: #fff2df;
        }

        .ZebraNo {
            color: black;
            background-color: #e8f1f9;
        }

        .ZebraTo {
            color: black;
            background-color: #ffffff;
        }
        /* 遮罩层样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }

        /* 模态框内容样式 */
        .modal-content {
            background-color: #0d283f;
            border: 1px solid #007297;
            margin: 10% auto;
            padding: 20px;
            width: 25%;
        }

        .modal-title {
            font-weight: bold;
        }

        /* 关闭按钮样式 */
        .close {
            color: #fff;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        /* 关闭按钮鼠标悬停样式 */
        .close:hover,
        .close:focus {
            color: #0BC4E9;
            text-decoration: none;
            cursor: pointer;
        }

        /*网栅格*/
        .form-flex {
            display: flex;
            flex-direction: column;
            gap: 0.1rem;
            font-size: 0.15rem;
        }

        .form-flex label {
            font-size: 0.15rem;
            font-weight: bold;
        }

        .form-flex .text {
            background-color: #0D283F;
            height: 100px;
            border: 1px solid #007297;
        }

        .form-flex input,
        .form-flex select,
        .form-flex textarea {
            border-radius: 5px;
            background-color: #0D283F;
            padding: 8px;
            border: 1px solid #007297;
        }

        .modaltable > tbody > tr > td > input,
        .modaltable > tbody > tr > td > select,
        .modaltable > tbody > tr > td > textarea {
            background-color: #0D283F;
            border: 1px solid #007297;
        }

        .form-flex button {
            /*background-color: #4CAF50;*/
            background-color: #07a3fd;
            color: white;
            padding: 0.06rem 0.2rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .form-flex button:hover {
            /*background-color: #45a049;*/
            background-color: #2665f8;
        }

        .form-flex > select,
        .form-flex > input,
        .form-flex > textarea {
            background-color: #0D283F;
            border: 1px solid #007297;
        }

        .form-flex > select:hover,
        .form-flex > input:hover,
        .form-flex > textarea:hover {
            background-color: #2C3444;
        }

        button[type="submit"] {
            font-size: .16rem;
            padding: 0.41em 2em;
            text-align: center;
        }
        /*选项卡*/
        .tab {
            overflow: hidden;
            width: 100%;
            height: 0.6rem;
            padding-left: 0.1rem;
            padding-right: 0.1rem;
        }

        .tab button {
            background-color: inherit;
            float: left;
            border: none;
            outline: none;
            cursor: pointer;
            font-size: 0.14rem;
            padding: 0.08rem 0.1rem;
            transition: 0.3s;
            border-bottom: 3px solid #509eb8;
        }

        .tab button:hover {
            background-color: #0aa9cd;
        }

        .tab button.active {
            color: white;
            background-color: #007297;
            border-bottom: 3px solid #0000ff;
            text-shadow: 0 0 0.2rem #00d8ff;
        }

        .tabcontent {
            padding: 6px 12px;
            border-top: none;
            width: 100%;
            height: 4.6rem;
        }

        .remark {
            float: right;
        }

        .required {
            color: red;
            font-weight: bolder;
        }

        .tooltip > p {
            height: 0.25rem;
            line-height: 0.25rem;
        }

        .tooltip > p > label, .tooltip > p > span {
            color: #2C3444;
            height: 0.2rem;
            font-family: Arial;
            font-size: 0.14rem;
            font-weight: bold;
        }

        .tooltip > p > span {
            float: right;
        }

        .tab > button {
            background-color: #509eb8;
        }

        .tab > button:hover, #cmb_data_type:hover {
            background-color: #0aa9cd;
        }

        #cmb_data_type {
            color: white;
            width: 1.2rem;
            height: 0.3rem;
            text-align: center;
            font-size: 0.14rem;
            border-radius: 5px;
            background-color: #007297;
            border: 1px solid #007297;
            text-shadow: 0 0 0.2rem #00d8ff;
        }

        #Tab1 {
            background-image: url('../images/loading1.gif');
            background-size: 0.8rem 0.8rem;
            background-repeat: no-repeat;
            background-position: center;
        }

    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="Uploading('SupplierPN')">数据上传</a>
                                <a class="menudropdown" onclick="DataToExcel('SupplierPN')">数据导出</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="query">
                        <input type="date" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time">
                        <span class="exampleInputProject tle">@Label.To</span>
                        <input type="date" id="enddate" name="enddate" placeholder="@Label.Start@Label.End">
                        <select id="cmb_wafer_id" name="Parameter" placeholder="select Wafer_ID">
                            <option value="">@Label.PleaseSelect</option>
                        </select>
                        <select id="cmb_lot_no" name="Parameter" style="width: 1.8rem;" placeholder="select Lot_No">
                            <option value="">@Label.PleaseSelect</option>
                        </select>
                        <select id="cmb_pn_parm" name="Parameter" style="width: 2.5rem;" placeholder="select Parameter">
                            <option value="">@Label.PleaseSelect</option>
                        </select>
                        <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="Getdata()">@Label.Query</button>
                    </div>
                    <div style="height: 10.15rem; background-color: white; border-radius: 5px;">
                        <div class="tab">
                            <button class="tablinks active" onclick="OpenTab(event,'tab','Tab1',waferparamboxplot)">Wafer&nbsp;Param&nbsp;Chart</button>
                            <button class="tablinks" onclick="OpenTab(event,'tab','Tab1',waferbylotboxplot)">Wafer&nbsp;By&nbsp;LotNo&nbsp;Param&nbsp;Chart</button>
                            <div style="float: right; line-height:0.5rem;">
                                <select id="cmb_data_type"></select>
                            </div>
                        </div>
                        <div id="Tab1" class="chart" style="height:95%;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        $("#cmb_data_type").hide();
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });

            function numberToUpperCase(number) {
                var uppercaseMonths = ['一月', '二月', '三月', '四月', '五月', '六月','七月', '八月', '九月', '十月', '十一月', '十二月'];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 6);
            $('.header-title').html("@Label.Board_IncomingParam");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear(); //年
                var myMonth = myDate.getMonth() + 1; //月
                var myToday = myDate.getDate(); //日
                var myDay = myDate.getDay(); //星期
                var myHour = myDate.getHours(); //小时
                var myMinute = myDate.getMinutes(); //分钟
                var mySecond = myDate.getSeconds(); //秒数
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);

            //设置全屏
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    //判断浏览器设备类型
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {       //兼容火狐
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {    //兼容谷歌
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {        //兼容IE
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit+Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });

            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                $('#enddate').val('');
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                var maxDate = new Date(startDate);
                maxDate.setMonth(maxDate.getMonth() + 6);
                if (endDate > maxDate) {
                    $('#enddate').val('');
                    alert('查询范围不能超过6个月！');
                } else {
                    endDate.setDate(endDate.getDate() - 1);
                    var maxStartDate = endDate.toISOString().split('T')[0];
                    $('#startdate').attr('max', maxStartDate);
                    if (startDate > endDate) {
                        $('#startdate').val($(this).val());
                    }
                }
            });
        });

        //下拉框
        $(function () {
            /*
            var startDate = new Date();
            startDate.setMonth(startDate.getMonth() - 4);
            var endDate = new Date();
            endDate.setDate(endDate.getDate() + 1);
            $('#startdate').val(startDate.toISOString().split('T')[0]);
            $('#enddate').val(endDate.toISOString().split('T')[0]);
            */

            $('#startdate').val('2024-08-01');
            $('#enddate').val('2024-12-01');

            var wafer_id = $("#cmb_wafer_id");
            var lot_no = $("#cmb_lot_no");
            var pn_parm = $("#cmb_pn_parm");
            var cmb_data_type = $("#cmb_data_type");
            var pam = {};
            var header_key = {
                start: $("#startdate").val(),
                end: $("#enddate").val()
            };
            pam.header_key = JSON.stringify(header_key);
            loadData(wafer_id, api + '/ReportAction/GetWaferSupplierWaferCombox', false);
            loadData(cmb_data_type, api + '/ReportAction/GetWaferSupplierWaferCombox', false);
            wafer_id.change(function () {
                header_key.wafer_id = $(this).val();
                header_key.lot_no = lot_no.val();
                pam.header_key = JSON.stringify(header_key);
                loadData(lot_no, api + '/ReportAction/GetWaferSupplierLotNoCombox', false);
                loadData(pn_parm, api + '/ReportAction/GetWaferSupplierToPnParmCombox', true);
            });
            pn_parm.change(function () { Getdata(); });
            wafer_id.prop('selectedIndex', 0).trigger('change');
            lot_no.prop('selectedIndex', 0);
            cmb_data_type.prop('selectedIndex', 0);
            function loadData(selectElement, url, boolean) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: pam,
                    async: true,
                    dataType: "json",
                    success: function (data) {
                        var selectdata = data.ReturnData;
                        selectElement.empty();
                        if (selectdata.length <= 0) {
                            var option = "<option>@Html.Raw(Label.No+Label.Correlation+Label.Data)</option>";
                            selectElement.append(option);
                            return;
                        }
                        if (boolean) {
                            selectElement.append("<option value='-1'>@Html.Raw(Label.PleaseSelect)...</option>");
                        } else {
                            selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                        }
                        $.each(selectdata, function (key, value) {
                            selectElement.append($('<option>', {
                                value: value.Value,
                                text: value.Text
                            }));
                        });
                        if (url.includes("ToPnParm")) {
                            pn_parm.prop('selectedIndex', 1).trigger('change');
                        }
                    }
                });
            }
        });

        //定时10MM
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            Tabtimer = setInterval(function () {
                var endDate = new Date($("#enddate").val());
                if (endDate > new Date()) {
                    Getdata();
                    echartsautomatic();
                }
            }, 10 * 60 * 1000);
        }
        function loadingshow() {
            $('#Tab1').css('background-image', 'url("../images/loading1.gif")');
            $('#Tab1').css('background-size', '0.8rem 0.8rem');
            $('#Tab1').css('background-repeat', 'no-repeat');
            $('#Tab1').css('background-position', 'center');
        }
        function loadingnone() {
            $('#Tab1').css('background-image', 'none');
        }

        var ReturnData;
        var Getdata = function () {
            if ($('#cmb_pn_parm').prop('selectedIndex') > 0 && $("#startdate").val() && $("#enddate").val()) {
                loadingshow();
                $('#btn_query').prop('disabled', true);
                var header_key = {
                    start: $("#startdate").val(),
                    end: $("#enddate").val(),
                    lot_no: $("#cmb_lot_no").val(),
                    wafer_id: $("#cmb_wafer_id").val()
                };
                var pam = {};
                pam.type = $("#cmb_pn_parm").val();
                pam.header_key = JSON.stringify(header_key);
                $.ajax({
                    type: "POST",
                    url: api + "/ReportAction/GetWaferSupplierToPnDate",
                    data: pam,
                    async: true,
                    dataType: "json",
                    success: function (dt) {
                        loadingnone();
                        $('#btn_query').prop('disabled', false);
                        $('#cmb_data_type').prop('selectedIndex', 0);
                        ReturnData = dt.ReturnData;
                        waferparamboxplot();
                        TabInterval();
                    }
                });
            }
        }

        /*Tab手动切换*/
        function OpenTab(evt, panle, id, echar_name, itemindex = -1) {
            var i, tablinks;
            tablinks = document.getElementsByClassName(panle)[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
            }
            evt.currentTarget.className += " active";
            let chart = echarts.init(document.getElementById(id));
            chart.dispose();
            $('#cmb_data_type').prop('selectedIndex', 0);
            echar_name();
        }

        //页签选中
        var tablinksonclick = function (switch_on) {
            var i, tablinks;
            tablinks = document.getElementsByClassName('tab')[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
                //console.log(tablinks[0].className.includes("active"));
            }
            switch (switch_on) {
                case "waferparam":
                    tablinks[0].className += " active";
                    $("#cmb_data_type").hide();
                    break;
                case "waferbylot":
                    tablinks[1].className += " active";
                    $("#cmb_data_type").show();
                    break;
            }
        }

        //wafer下拉
        $('#cmb_data_type').on('change', function () {
            var i, tablinks;
            tablinks = document.getElementsByClassName("tab")[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                if (tablinks[i].className.includes("active")) {
                    switch (i) {
                        case 0:
                            $("#cmb_data_type").hide();
                            waferparamboxplot();
                            break;
                        case 1:
                            $("#cmb_data_type").show();
                            waferbylotboxplot();
                            break;
                    }
                }
            }
        });

        //Boxplot计算箱线图
        function calculateBoxplotStats(values) {
            values.sort((a, b) => a - b);
            const min = values[0];
            const max = values[values.length - 1];
            const q1 = values[Math.floor(values.length / 4)];
            const median = values[Math.floor(values.length / 2)];
            const q3 = values[Math.floor(values.length * 3 / 4)];
            return [min, q1, median, q3, max, values.length];
        }

        //WaferByLotNo
        function waferbylotData(data) {
            const groupedData = {};
            const uniqueLotNos = new Set();
            const uniqueWaferIDs = new Set();
            data.forEach(item => {
                const key = `${item.Wafer_ID}|${item.Lot_No}|${item.Parameter}`;
                if (!groupedData[key]) {
                    groupedData[key] = [];
                }
                groupedData[key].push(item.Value);
                uniqueLotNos.add(item.Lot_No);
                uniqueWaferIDs.add(item.Wafer_ID);
            });
            const boxplotData = [];
            const scatterData = [];
            const categories = {
                Wafer_ID: [],
                Lot_No: [],
                Parameter: []
            };
            Object.keys(groupedData).forEach((key, index) => {
                const [waferID, lotNo, parameter] = key.split('|');
                const values = groupedData[key];

                boxplotData.push(calculateBoxplotStats(values));
                values.forEach(value => scatterData.push([index, value]));
                categories.Wafer_ID.push(waferID);
                categories.Lot_No.push(lotNo);
                categories.Parameter.push(parameter);
            });
            return {
                boxplotData,
                scatterData,
                categories,
                uniqueLotNos: Array.from(uniqueLotNos),
                uniqueWaferIDs: Array.from(uniqueWaferIDs)
            };
        }
        function waferbylotboxplot() {
            $("#cmb_data_type").show();
            tablinksonclick("waferbylot");
            var cl_type = $('#cmb_data_type').val().toUpperCase();
            let filteredData;
            if (cl_type == 'ALL') {
                filteredData = ReturnData.Table;
            } else {
                filteredData = ReturnData.Table.filter(item => item.Wafer_ID === cl_type);
            }
            const lotData = waferbylotData(filteredData);
            const parameter = lotData.categories.Parameter;
            const lotno = lotData.uniqueLotNos;
            const wafer = lotData.uniqueLotNos.map(lot => lot.slice(0, 8));
            const medianData = lotData.boxplotData.map(box => box[2]);
            const option = {
                title: {
                    text: $("#cmb_pn_parm").val(),
                    textStyle: {
                        fontSize: '0.16rem',
                        color: '#007297'
                    }
                },
                textStyle: {
                    color: '#666',
                    fontSize: '0.16rem'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: (param) => {
                        if (param.seriesType === 'boxplot') {
                            return [
                                '散点数: ' + param.data[6],
                                'Upper: ' + param.data[5],
                                'Q3: ' + param.data[4],
                                'Median: ' + param.data[3],
                                'Q1: ' + param.data[2],
                                'Lower: ' + param.data[1]
                            ].join('<br/>');
                        } else {
                            return `${param.name}: ${param.value[1]}`;
                        }
                    }
                },
                grid: {
                    top: '10%',
                    right: '4%',
                    left: '4%',
                    width: '92%',
                    bottom: '38%'
                },
                xAxis: [
                    {
                        type: 'category',
                        data: parameter,
                        boundaryGap: true,
                        show: false,
                        name: 'Parameter',
                        splitArea: { show: true },
                        axisPointer: {
                            show: false
                        }
                    },
                    {
                        type: 'category',
                        data: lotno,
                        position: 'bottom',
                        name: 'LotNo',
                        offset: 10,
                        axisLabel: {
                            interval: lotno.length >= 115 ? Math.ceil(lotno.length / 115) : 0,
                            formatter: function (value) {
                                return value.split('').join('\n');
                            },
                            textStyle: {
                                fontSize: '0.14rem'
                            }
                        },
                        axisTick: {
                            interval: 0
                        }
                    },
                    {
                        type: 'category',
                        data: wafer,
                        position: 'bottom',
                        name: 'Wafer',
                        offset: 180,
                        axisPointer: {
                            show: false
                        },
                        axisLabel: {
                            interval: wafer.length >= 24 ? Math.ceil(wafer.length / 24) : 0,
                            textStyle: {
                                fontSize: '0.14rem'
                            }
                        }
                    }
                ],
                yAxis: {
                    type: 'value',
                    name: 'Value',
                    scale: true,
                    splitArea: {
                        show: true
                    }
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1],
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1],
                        handleSize: 0
                    }
                ],
                series: [
                    {
                        name: '散点图',
                        type: 'scatter',
                        data: lotData.scatterData,
                        /*高性能模式*/
                        //large: true,
                        //largeThreshold: 10000,
                        symbolSize: 10,
                        itemStyle: {
                            color: 'rgba(25, 100, 150, 0.5)',
                            borderWidth: 0
                        },
                        emphasis: {
                            itemStyle: {
                                color: 'rgb(128, 255, 165)',
                                borderColor: 'rgb(128, 255, 165)',
                                borderWidth: 0,
                            }
                        }
                    },
                    {
                        name: '箱线图',
                        type: 'boxplot',
                        data: lotData.boxplotData,
                        itemStyle: {
                            color: 'rgba(255, 255, 255, 0)',
                            borderColor: '#00DDFF',
                            borderWidth: 1.2
                        },
                        emphasis: {
                            itemStyle: {
                                borderColor: 'orange'
                            }
                        }
                    },
                    {
                        name: 'median',
                        type: 'line',
                        data: medianData.map((median, index) => [index, median]),
                        itemStyle: {
                            color: '#FF0087'
                        },
                        lineStyle: {
                            width: 2,
                            type: 'solid'
                        },
                        symbol: 'circle',
                        symbolSize: 6,
                        areaStyle: {
                            gradient: true,
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    { offset: 0, color: 'rgba(255, 0, 0, 0.3)' },
                                    { offset: 1, color: 'rgba(255, 0, 0, 0)' }
                                ],
                                global: false
                            }
                        }
                    },
                ]
            };
            var chartDom = document.getElementById("Tab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var myChart = echarts.init(chartDom, null, { renderer: 'canvas' });
            myChart.setOption(option);
            myChart.on('dataZoom', function (params) {
                const option = myChart.getOption();
                const xAxisData = option.xAxis[1].data;
                const start = option.dataZoom[0].start;
                const end = option.dataZoom[0].end;
                const startIndex = Math.round((xAxisData.length - 1) * (start / 100));
                const endIndex = Math.round((xAxisData.length - 1) * (end / 100));
                let visibleYData = lotno.slice(startIndex, endIndex + 1).map(lot => lot.slice(0, 8));
                const uniqueData = visibleYData.filter((item, index) => visibleYData.indexOf(item) === index);
                myChart.setOption({
                    xAxis: [
                        {
                            data: parameter,
                        },
                        {
                            data: lotno,
                            axisLabel: {
                                interval: visibleYData.length >= 115 ? Math.ceil(visibleYData.length / 115) : 0,
                                formatter: function (value) {
                                    return value.split('').join('\n');
                                }
                            }
                        },
                        {
                            data: uniqueData,
                            axisLabel: {
                                interval: uniqueData.length >= 24 ? Math.ceil(uniqueData.length / 24) : 0,
                                interval: 0
                            }
                        }
                    ]
                });
            });
            window.addEventListener('resize', function () {
                myChart.resize();
            });
        }

        //Wafer
        function waferparamData(data) {
            const groupedData = {};
            const uniqueWaferIDs = new Set();
            data.forEach(item => {
                const key = `${item.Wafer_ID}|${item.Parameter}`;
                if (!groupedData[key]) {
                    groupedData[key] = [];
                }
                groupedData[key].push(item.Value);
                uniqueWaferIDs.add(item.Wafer_ID);
            });
            const boxplotData = [];
            const scatterData = [];
            const categories = {
                Wafer_ID: [],
                Parameter: []
            };
            Object.keys(groupedData).forEach((key, index) => {
                const [waferID, parameter] = key.split('|');
                const values = groupedData[key];
                boxplotData.push(calculateBoxplotStats(values));
                values.forEach(value => scatterData.push([index, value]));
                categories.Wafer_ID.push(waferID);
                categories.Parameter.push(parameter);
            });
            return {
                boxplotData,
                scatterData,
                categories,
                uniqueWaferIDs: Array.from(uniqueWaferIDs)
            };
        }
        function waferparamboxplot() {
            $("#cmb_data_type").hide();
            tablinksonclick("waferparam");
            var cl_type = $('#cmb_data_type').val().toUpperCase();
            let filteredData;
            if (cl_type == 'ALL') {
                filteredData = ReturnData.Table;
            } else {
                filteredData = ReturnData.Table.filter(item => item.Wafer_ID === cl_type);
            }
            const waferData = waferparamData(filteredData);
            const parameter = waferData.categories.Parameter;
            const wafer = waferData.uniqueWaferIDs;
            const medianData = waferData.boxplotData.map(box => box[2]);
            const option = {
                title: {
                    text: $("#cmb_pn_parm").val(),
                    textStyle: {
                        fontSize: '0.16rem',
                        color: '#007297'
                    }
                },
                textStyle: {
                    color: '#666',
                    fontSize: '0.16rem'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: (param) => {
                        if (param.seriesType === 'boxplot') {
                            return [
                                '散点数: ' + param.data[6],
                                'Upper: ' + param.data[5],
                                'Q3: ' + param.data[4],
                                'Median: ' + param.data[3],
                                'Q1: ' + param.data[2],
                                'Lower: ' + param.data[1]
                            ].join('<br/>');
                        } else {
                            return `${param.name}: ${param.value[1]}`;
                        }
                    }
                },
                grid: {
                    top: '10%',
                    right: '4%',
                    left: '4%',
                    width: '92%',
                    bottom: '25%'
                },
                xAxis: [
                    {
                        type: 'category',
                        data: parameter,
                        boundaryGap: true,
                        show: false,
                        name: 'Parameter',
                        splitArea: { show: true },
                        axisPointer: {
                            show: false
                        }
                    },
                    {
                        type: 'category',
                        data: wafer,
                        position: 'bottom',
                        name: 'Wafer',
                        offset: 10,
                        axisLabel: {
                            interval: wafer.length >= 115 ? Math.ceil(wafer.length / 115) : 0,
                            formatter: function (value) {
                                return value.split('').join('\n');
                            },
                            textStyle: {
                                fontSize: '0.14rem'
                            }
                        },
                        axisTick: {
                            interval: 0
                        }
                    }
                ],
                yAxis: {
                    type: 'value',
                    name: 'Value',
                    scale: true,
                    splitArea: {
                        show: true
                    }
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1],
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1],
                        handleSize: 0
                    }
                ],
                series: [
                    {
                        name: '散点图',
                        type: 'scatter',
                        data: waferData.scatterData,
                        /*高性能模式*/
                        //large: true,
                        //largeThreshold: 10000,
                        symbolSize: 10,
                        itemStyle: {
                            color: 'rgba(25, 100, 150, 0.5)',
                            borderWidth: 0
                        },
                        emphasis: {
                            itemStyle: {
                                color: 'rgb(128, 255, 165)',
                                borderColor: 'rgb(128, 255, 165)',
                                borderWidth: 0
                            }
                        }
                    },
                    {
                        name: '箱线图',
                        type: 'boxplot',
                        data: waferData.boxplotData,
                        itemStyle: {
                            color: 'rgba(255, 255, 255, 0)',
                            borderColor: '#00DDFF',
                            borderWidth: 1.2
                        },
                        emphasis: {
                            itemStyle: {
                                borderColor: 'orange'
                            }
                        }
                    },
                    {
                        name: 'median',
                        type: 'line',
                        data: medianData.map((median, index) => [index, median]),
                        itemStyle: {
                            color: '#FF0087'
                        },
                        lineStyle: {
                            width: 2,
                            type: 'solid'
                        },
                        symbol: 'circle',
                        symbolSize: 6,
                        areaStyle: {
                            gradient: true,
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    { offset: 0, color: 'rgba(255, 0, 0, 0.3)' },
                                    { offset: 1, color: 'rgba(255, 0, 0, 0)' }
                                ],
                                global: false
                            }
                        }
                    },
                ]
            };
            var chartDom = document.getElementById("Tab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var myChart = echarts.init(chartDom, null, { renderer: 'canvas' });
            myChart.setOption(option);
            window.addEventListener('resize', function () {
                myChart.resize();
            });
        }

        //Uploading
        function Uploading() {
            alert("暂未开放权限,请联系管理人员....");
        }

        //DataToExcel
        var ExportType;
        function DataToExcel(type) {
            var formData = new FormData();
            formData.append('start', $("#startdate").val());
            formData.append('end', $("#enddate").val());
            formData.append('lot_no', $('#cmb_lot_no').val() == null ? "ALL" : $('#cmb_lot_no').val());
            formData.append('wafer_id', $('#cmb_wafer_id').val() == null ? "ALL" : $('#cmb_wafer_id').val());
            formData.append('excelname', type);
            ExportType = type;
            var url = api + "/ReportAction/GetWaferSupplierDataToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }
    </script>
</body>
</html>
